package com.dhecp.project.business.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductHistory;
import com.dhecp.project.business.mapper.ProductHistoryMapper;
import com.dhecp.project.business.service.ProductHistoryService;
import com.dhecp.project.common.domain.DataBaseMessage;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 产品表  业务实现层
 * @author DH-Xxj
 * @version 2019年11月12日
 */
@Service
public class ProductHistoryServiceImpl implements ProductHistoryService {

	@Autowired
	private ProductHistoryMapper productHistoryMapper;

	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;
	
	/**
	 * 查询所有产品信息
	 * @param params
	 * @return List-ProductHistory
	 * @author lwl
	 * @throws Exception 
	 */
	@Override
	public List<ProductHistory> queryProductInfo(Map<String, Object> params) throws Exception{
		params.put("wherestr", dictionaryForFieldService.getWhereStr(params));

		if (params.get("field") == null || params.get("field") == ""){
			String orderBy = "GBrand,GID asc";
			PageUtils.startPageOrder(orderBy);
		}else{
			PageUtils.startPage();	
		}	
		
		return productHistoryMapper.findProductInfo(params);
	}
	
	/**
	 * 通过guid查询单条记录
	 * @param guid
	 * @return 实体ProductInfo
	 * @author lwl
	 */
	@Override
	public ProductHistory queryProductInfoByGuid(String guid) {
		return productHistoryMapper.findProductInfoByGuid(guid);
	}

	/*@Override
	public AjaxResult importProduct(List<ProductHistory> productList,boolean isUpdateSupport) {
		if (productList == null || productList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
		for(ProductHistory ProductHistory:productList){
			if (productHistoryMapper.findProductInfoByGBrand(ProductHistory)==null) {
				ProductHistory.setCreateUser(ShiroUtils.getUserId());
				ProductHistory.setCreateTime(new Date());
				productHistoryMapper.insertProductInfo(ProductHistory);
				return AjaxResult.success("导入成功");
			}else if(isUpdateSupport){
				ProductHistory.setUpdateUser(ShiroUtils.getUserId());
				ProductHistory.setUpdateTime(new Date());
				productHistoryMapper.updateProduct(ProductHistory);
				return AjaxResult.success("更新成功");
			}else{
				return AjaxResult.error("产品已存在");
			}
		}
		
		return AjaxResult.success("数据已全部导入成功");
	}*/
	
	
	/**
	 * 新增产品信息
	 * @param productInfoItems
	 * @param fSl   面价（含税/未税）计算税率
	 * @param fType 面价（含税/未税）计算类型：（fType == 1：含税面价计算未税面价，fType == 0：未税面价计算含税面价）
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult insertProduct(Map<String, Object> params) {
		if (StringUtils.isEmpty(params)) {
			return AjaxResult.error("数据提交失败，必填参数有误！");
		}
		if (params.get("vCpFl") == null || params.get("vCpFl") == ""){
			return AjaxResult.error("请将选择产品分类！");
		}
		Double fSl = 0.0;
		Integer fType = 2;		
		if (params.get("fSl") != null && params.get("fSl") != ""){
			fSl = Double.valueOf(params.get("fSl").toString());
		}
		if (params.get("fType") != null && params.get("fType") != ""){
			fType = Integer.valueOf(params.get("fType").toString());
		}
		List<ProductHistory> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductHistory.class);
		if (productInfoList == null || productInfoList.size() == 0) {
			return AjaxResult.error("请添加需要保存的产品信息。");
		}

		for (ProductHistory ProductHistory : productInfoList) {
			AjaxResult ajaxResult = checkedProductKey(ProductHistory);
			if (!"0".equals(ajaxResult.get("code").toString())){
				return ajaxResult;
			}
		}
		
		for (ProductHistory ProductHistory : productInfoList) {
			ProductHistory.setCreateUser(ShiroUtils.getUserId());
			ProductHistory.setCreateTime(new Date());
			if (fType == 1){	//含税面价计算未税面价
				if(ProductHistory.getfHsMj() == null)ProductHistory.setfHsMj(0.00);
				ProductHistory.setfWsMj(ProductHistory.getfHsMj()*100/(100+fSl));
			}
			if (fType == 0){	//未税面价计算含税面价
				if(ProductHistory.getfWsMj() == null)ProductHistory.setfWsMj(0.00);
				ProductHistory.setfHsMj(ProductHistory.getfWsMj()*(100+fSl)/100);
			}
			if (productHistoryMapper.findProductInfoByGBrand(ProductHistory) != null){
				productHistoryMapper.updateProduct(ProductHistory);
			}else{
				productHistoryMapper.insertProductInfo(ProductHistory);
			}
		}
		return AjaxResult.success("操作成功");
	}
	
	/**
	 * 清理产品导入过渡表中遗留的数据
	 * @param params
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult cleanProductInfoImport(Map<String, Object> params) {
		params.put("sessionId", ShiroUtils.getSessionId());
		DataBaseMessage dataBaseMessage = productHistoryMapper.cleanProductInfoImport(params);
		
		if ("0".equals(dataBaseMessage.getCode())){
			return AjaxResult.success(dataBaseMessage.getMsg());
		}else if ("301".equals(dataBaseMessage.getCode())){
			return AjaxResult.warn(dataBaseMessage.getMsg());
		}else if ("500".equals(dataBaseMessage.getCode())){
			return AjaxResult.error(dataBaseMessage.getMsg());
		}else{
			return AjaxResult.error("未知服务器错误，请重试。");
		}
	}

	/**
	 * 将本次导入的产品数据从产品导入过渡表中转入产品信息正式表
	 * @param records 导入总记录数int类型
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult importToProductInfo(Map<String, Object> params) {
		params.put("sessionId", ShiroUtils.getSessionId());
		if (params.get("records") == null){
			params.put("records", 0);
		}
		DataBaseMessage dataBaseMessage = productHistoryMapper.importToProductInfo(params);
		
		if ("0".equals(dataBaseMessage.getCode())){
			return AjaxResult.success(dataBaseMessage.getMsg());
		}else if ("301".equals(dataBaseMessage.getCode())){
			return AjaxResult.warn(dataBaseMessage.getMsg());
		}else if ("500".equals(dataBaseMessage.getCode())){
			return AjaxResult.error(dataBaseMessage.getMsg());
		}else{
			return AjaxResult.error("未知服务器错误，请重试。");
		}
	}
	
	/**
	 * 导入产品信息至产品信息过渡表
	 * @param productInfoItems
	 * @param fSl   面价（含税/未税）计算税率
	 * @param fType 面价（含税/未税）计算类型：（fType == 1：含税面价计算未税面价，fType == 0：未税面价计算含税面价）
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult importProduct(Map<String, Object> params) {
		if (StringUtils.isEmpty(params)) {
			return AjaxResult.error("数据提交失败，必填参数有误！");
		}
		Double fSl = 0.0;
		Integer fType = 2;		
		if (params.get("fSl") != null && params.get("fSl") != ""){
			fSl = Double.valueOf(params.get("fSl").toString());
		}
		if (params.get("fType") != null && params.get("fType") != ""){
			fType = Integer.valueOf(params.get("fType").toString());
		}
		List<ProductHistory> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductHistory.class);
		if (productInfoList == null || productInfoList.size() == 0) {
			return AjaxResult.error("数据包格式有误，请检查！");
		}

		for (ProductHistory ProductHistory : productInfoList) {
			AjaxResult ajaxResult = checkedProductKey(ProductHistory);
			if (!"0".equals(ajaxResult.get("code").toString())){
				return ajaxResult;
			}
		}

		for (ProductHistory ProductHistory : productInfoList) {
			ProductHistory.setCreateUser(ShiroUtils.getUserId());
			ProductHistory.setCreateTime(new Date());
			ProductHistory.setSessionId(ShiroUtils.getSessionId());
			if (fType == 1){	//含税面价计算未税面价
				if(ProductHistory.getfHsMj() == null)ProductHistory.setfHsMj(0.00);
				ProductHistory.setfWsMj(ProductHistory.getfHsMj()*100/(100+fSl));
			}
			if (fType == 0){	//未税面价计算含税面价
				if(ProductHistory.getfWsMj() == null)ProductHistory.setfWsMj(0.00);
				ProductHistory.setfHsMj(ProductHistory.getfWsMj()*(100+fSl)/100);
			}
			productHistoryMapper.importProductInfo(ProductHistory);
		}
		return AjaxResult.success("操作成功");
	}

	/**
	 * 修改产品信息
	 * @param productInfoItems
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult updateProduct(Map<String, Object> params) {
		List<ProductHistory> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductHistory.class);
		if (productInfoList == null || productInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
		
		for (ProductHistory ProductHistory : productInfoList) {
			ProductHistory.setUpdateUser(ShiroUtils.getUserId());
			ProductHistory.setUpdateTime(new Date());			
			if (productHistoryMapper.findProductInfoByGBrandAndGuid(ProductHistory) != null) {
				return AjaxResult.error("已有相同【品牌、型号、规格、单位】的产品信息，请检查！");
			}else{
				productHistoryMapper.updateProduct(ProductHistory);
			}
		}
		return AjaxResult.success("操作成功！");
	}

	/**
	 * 通过Guid删除产品信息
	 * @param productInfoItems
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult deleteProductInfoByGuid(Map<String, Object> params) {
		List<ProductHistory> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductHistory.class);
		if (productInfoList == null || productInfoList.size() == 0) {
			return AjaxResult.error("数据包格式有误，请检查！");
		}
		for (ProductHistory ProductHistory : productInfoList) {
			productHistoryMapper.deleteByGuid(ProductHistory);
		}
		return AjaxResult.success("操作成功");
	}

	/**
	 * 验证产品主键是否为空
	 * @param ProductHistory
	 * @return
	 * @author DH-Xxj
	 */
	private AjaxResult checkedProductKey(ProductHistory ProductHistory){
		if (StringUtils.isEmpty(ProductHistory.getgBrand()) || StringUtils.isEmpty(ProductHistory.getgID())){
			return AjaxResult.error("【品牌、型号】不能为空，请删除或修改存在空值的产品信息。");
		}
		return AjaxResult.success();
	}
	
}
